package cn.task.part2.part1.window;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import cn.task.part2.part1.utils.IdentifyString;

public class ConsonantsWindow extends JPanel implements ActionListener{
	JLabel[] labels;
	String[] labelNames={"输入字符串："};
	JTextField englishString;
	
	JButton inputButton,resetButton;
	
	public void init(){
		Font labelFont=new Font("宋体",Font.PLAIN,20); //标签字体
		labels=new JLabel[labelNames.length];
		for(int i=0;i<labelNames.length;i++){
			labels[i]=new JLabel(labelNames[i],JLabel.CENTER);
			labels[i].setFont(labelFont);
		}
		
		englishString=new JTextField(20);
		englishString.setFont(labelFont);
		
		inputButton=new JButton("识别辅音");
		resetButton=new JButton("重置");
		
		Box[] horiBoxes=new Box[labelNames.length];
		for(int i=0;i<labelNames.length;i++){
			horiBoxes[i]=Box.createHorizontalBox();
			horiBoxes[i].add(labels[i]);
		}
		horiBoxes[0].add(englishString);
		
		Box verticalBox=Box.createVerticalBox();
		for(int i=0;i<labelNames.length;i++){
			verticalBox.add(horiBoxes[i]);
			verticalBox.add(Box.createVerticalStrut(15));
		}
		
		JPanel centerPanel=new JPanel();
		centerPanel.setOpaque(false);
		centerPanel.add(verticalBox);
		JPanel buttonPanel =new JPanel();
		buttonPanel.add(inputButton);
		buttonPanel.add(resetButton);
		inputButton.addActionListener(this);
		resetButton.addActionListener(this);
		
		//设置边界式布局
		this.setLayout(new BorderLayout());
		this.add(centerPanel,BorderLayout.CENTER);
		this.add(buttonPanel,BorderLayout.SOUTH);
	}
	public ConsonantsWindow(){
		init();
	}
	
	
	public boolean isLegal(String str){//判断文本框内的内容是否非空
		if(str==null || str.equals("") || str.contains(" "))
			return false;
		return true;
	}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getActionCommand().equals("重置")){//点击了重置按钮
			englishString.setText("");
		}else {//点击了录入按钮
			if(!isLegal(englishString.getText())) {
				JOptionPane.showMessageDialog(this, "您输入的学号不规范：学号为空或包含空格！",
						"学号非法",JOptionPane.OK_OPTION);
				englishString.requestFocus();
				englishString.selectAll();
			}else {
				int count = IdentifyString.count(englishString.getText(), "consonants");
				JOptionPane.showMessageDialog(this, "您输入的字符串包含的辅音个数"+count,
						"插入提示",JOptionPane.PLAIN_MESSAGE);
				IdentifyString.destory();
			}
		}
		
	}
}
